package org.jeecg.modules.chg.controller;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.vo.JwidModel;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.WeChatPayModel;
import org.jeecg.common.util.pay.WXPayUtils;
import org.jeecg.config.mybatis.TenantContext;
import org.jeecg.modules.arc.service.IArcAccountService;
import org.jeecg.modules.chg.service.IChgArrearsService;
import org.jeecg.modules.chg.service.IChgFeesService;
import org.jeecg.modules.chg.service.IChgMpService;
import org.jeecg.modules.chg.service.IChgPaymentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
* @Description: MP-pay
* @Author: jeecg-boot
* @Date:   2022-02-21
* @Version: V1.0
*/
@Api(tags="wxpay")
@RestController
@RequestMapping("/chg/mp")
@Slf4j
public class ChgMpController {

    @Autowired
    private IArcAccountService accountService;
    @Autowired
    private IChgArrearsService arrearsService;
    @Autowired
    private IChgFeesService chgFeesService;
    @Autowired
    private IChgPaymentsService paymentsService;


    @Autowired
    private IChgMpService chgMpService;
    @Autowired
    private WXPayUtils wxPayUtils;
    @Autowired
    private ISysBaseAPI sysBaseAPI;

    private WeChatPayModel payModel;

    //@Autowired
    //private WechatPayConfig wechatPayConfig;
    //@Autowired
    //private ProductOrderService productOrderService;
    //@Autowired
    //private CertificatesVerifier verifier;

    /**
     * 下单
     *
     * @param orderObj
     * @return
     */
    @AutoLog(value = "下单")
    @ApiOperation(value = "下单", notes = "下单")
    @PostMapping(value = "/createOrder")
    public Result<?> createOrder(@RequestBody JSONObject orderObj, HttpServletRequest request)
            throws Exception {
        // 将jwid信息放入
        String jwid = request.getHeader(CommonConstant.X_JWID);
        String openid = request.getHeader(CommonConstant.X_OPENID);

        if(null != orderObj ){

            JSONObject object = new JSONObject();
            object.put("jwid",jwid);//gh_78b3defc9ec3
            JwidModel jwidModel = sysBaseAPI.getJwId(object);

            jwidModel.setOpenId(openid);
            int tid= Integer.parseInt(TenantContext.getTenant());
            String s = String.format("%0" + 4 + "d", tid);
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

            orderObj.put("createBy",sysUser.getUsername());

            return chgMpService.createMpOrder(jwidModel,orderObj);

        }
        return Result.error("没有欠费记录");

    }

    /**
     * 客户端支付成功-查询订单状态-核销
     *
     * @param orderObj
     * @return
     */
    @AutoLog(value = "客户端支付成功-查询订单状态-核销")
    @ApiOperation(value = "客户端支付成功-查询订单状态-核销", notes = "客户端支付成功-查询订单状态-核销")
    @PostMapping(value = "/queryOrder")
    public Result<?> queryOrder(@RequestBody JSONObject orderObj, HttpServletRequest request)
            throws Exception {
        // 将jwid信息放入  if(null != orderObj && null != orderObj.get("package")) {
        String jwid = request.getHeader(CommonConstant.X_JWID);
        String openId = request.getHeader(CommonConstant.X_OPENID);

        if(null != orderObj &&  null != orderObj.get("package")){

            JSONObject object = new JSONObject();
            object.put("jwid",jwid);
            JwidModel jwidModel = sysBaseAPI.getJwId(object);
            jwidModel.setOpenId(openId);

            return chgMpService.queryMpOrderState(jwidModel,orderObj);

        }
        return Result.error("支付异常");

    }



        /**
         * 支付通知回调
         * @param request
         * @param response
         * @return
         */
        @PostMapping(value = "/orderNotify")
        @ResponseBody
        public Map<String, String> wehcatPayCallback(HttpServletRequest request, HttpServletResponse response) {

            //获取报文
            String body = getRequestBody(request);
            //随机串
            String nonceStr = request.getHeader("Wechatpay-Nonce");
            //微信传递过来的签名
            String signature = request.getHeader("Wechatpay-Signature");
            //证书序列号（微信平台）
            String serialNo = request.getHeader("Wechatpay-Serial");
            //时间戳
            String timestamp = request.getHeader("Wechatpay-Timestamp");

            //支付通知不确定 租户身份

//            System.out.println(request.getParameter("attach"));
//            //确定租户  attach
//            String[] nonceArr = nonceStr.split("_");
//            String tenantId= "16";//nonceArr[1];
//
//            JSONObject object = new JSONObject();
//            object.put("tenantId",tenantId);
//            JwidModel jwidModel = sysBaseAPI.getJwId(object);
//            System.out.println(jwidModel.getName());
//
//            Result<?> result = chgMpService.wehcatPayback(jwidModel, body, nonceStr, serialNo, signature, timestamp);
//            if(result.isSuccess()){
//                Map map=new HashMap();
//                map.put("code", "SUCCESS");
//                map.put("message", "成功");
//
//                return map;
//            }
            return null;
        }


        /**
         * 转换body为map
         * @param plainBody
         * @return
         */
        private Map<String,String> convertWechatPayMsgToMap(String plainBody){

            Map<String,String> paramsMap = new HashMap<>(2);
            JSONObject jsonObject = JSONObject.parseObject(plainBody);
            //商户订单号
            paramsMap.put("out_trade_no",jsonObject.getString("out_trade_no"));
            //交易状态
            paramsMap.put("trade_state",jsonObject.getString("trade_state"));
            //附加数据
            paramsMap.put("account_no",jsonObject.getJSONObject("attach").getString("accountNo"));
            return paramsMap;
        }


        ///**
        // * 验证签名
        // *
        // * @param serialNo  微信平台-证书序列号
        // * @param signStr   自己组装的签名串
        // * @param signature 微信返回的签名
        // * @return
        // * @throws UnsupportedEncodingException
        // */
        //private boolean verifiedSign(String serialNo, String signStr, String signature) throws UnsupportedEncodingException {
        //    return verifier.verify(serialNo, signStr.getBytes("utf-8"), signature);
        //}


    /**
     * 读取请求数据流
     *
     * @param request
     * @return
     */
    private String getRequestBody(HttpServletRequest request) {

        StringBuffer sb = new StringBuffer();

        try (ServletInputStream inputStream = request.getInputStream();
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        ) {
            String line;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }

        } catch (IOException e) {
            log.error("读取数据流异常:{}", e);
        }

        return sb.toString();

    }






}
